﻿using Fabrikam.Client.DataModel;
using Fabrikam.Client.ViewModels;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Settings Flyout item template is documented at http://go.microsoft.com/fwlink/?LinkId=273769

namespace Fabrikam.Client
{
    public sealed partial class SettingsFlyoutItem : SettingsFlyout
    {
        private Popup parent;
        private SettingFlyoutItemViewModel context;
        private TaskCompletionSource<Boolean> tcs;

        public SettingsFlyoutItem()
        {
            this.InitializeComponent();
            this.BackClick += SettingsFlyoutItem_BackClick;
            this.Loaded += SettingsFlyoutItem_Loaded;
            this.context = DataContext as SettingFlyoutItemViewModel;
        }

        void SettingsFlyoutItem_Loaded(object sender, RoutedEventArgs e)
        {
            this.parent = Parent as Popup;

            if (this.parent != null)
                this.parent.Closed += parent_Closed;

        }

        void parent_Closed(object sender, object e)
        {
            if (this.tcs.Task.Status != TaskStatus.RanToCompletion)
                this.tcs.SetResult(false);

            if (this.context.tcs.Task.Status != TaskStatus.RanToCompletion)
                this.context.tcs.SetResult(false);
        }


        public async Task<Boolean> ShowIndependentAsync()
        {
            this.ShowIndependent();

            this.tcs = new TaskCompletionSource<Boolean>();

            //Await the completion from any event handler
            await Task.Factory.StartNew(() =>
                    Task.WaitAll(new Task[] { tcs.Task, this.context.tcs.Task }));

            this.Hide();

            if (tcs.Task.Result == false || context.tcs.Task.Result == false)
                return false;

            return true;
        }


        void SettingsFlyoutItem_BackClick(object sender, BackClickEventArgs e)
        {
            this.tcs.SetResult(false);
        }
        private void OkButton_Click(object sender, RoutedEventArgs e)
        {

            this.tcs.SetResult(true);
        }
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.tcs.SetResult(false);

        }

    }
}
